
package com.example;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.*;

@WebServlet("/books")
public class BookServlet extends HttpServlet {
    private Connection conn;
    
    @Override
    public void init() throws ServletException {
        try {
            String url = getServletContext().getInitParameter("dbURL");
            String user = getServletContext().getInitParameter("dbUser");
            String password = getServletContext().getInitParameter("dbPassword");
            
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            throw new ServletException("DB connection failed", e);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        try {
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM books");
            request.setAttribute("books", rs);
            request.getRequestDispatcher("/books.jsp").forward(request, response);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        
        try (PreparedStatement pstmt = conn.prepareStatement(
                "INSERT INTO books (title, author) VALUES (?, ?)")) {
            pstmt.setString(1, title);
            pstmt.setString(2, author);
            pstmt.executeUpdate();
            response.sendRedirect("books");
        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
    
    @Override
    public void destroy() {
        try {
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
